<template>
  <view>
    <view class="container">
      <view class="submit-order">
        <!-- 自提地址 -->
        <view class="delivery-addr " v-if="ifBao == 1">
          <view class="addr-bg whole">
            <view class="addr-icon">
              <image src="@/static/images/icon/addr.png" />
            </view>
            <view class="user-info">
              <text class="item">
                {{ schoolInfo && schoolInfo.linkName }}
              </text>
              <text class="item">
                {{ schoolInfo && schoolInfo.linkPhone }}
              </text>
            </view>
            <view class="addr">
              {{ schoolInfo && schoolInfo.linkAddress }}
            </view>
          </view>
        </view>
        <!-- 收货地址 -->
        <view
          class="delivery-addr "
          @tap="toAddrListPage"
          v-else
        >
          <view
            v-if="!userAddr"
            class="addr-bg "
          >
            <view class="add-addr">
              <view class="plus-sign-img">
                <image src="@/static/images/icon/plus-sign.png" />
              </view>
              <text>新增收货地址</text>
            </view>
            <view class="arrow empty" />
          </view>
          <view
            v-if="userAddr"
            class="addr-bg whole"
          >
            <view class="addr-icon">
              <image src="@/static/images/icon/addr.png" />
            </view>
            <view class="user-info">
              <text class="item">
                {{ userAddr.name }}
              </text>
              <text class="item">
                {{ userAddr.phone }}
              </text>
            </view>
            <view class="addr">
              {{ userAddr.address }}{{ userAddr.addressInfo }}
            </view>
            <view class="arrow" />
          </view>
        </view>

        <!-- 商品详情 -->
        <view class="prod-item">
          <block
            v-for="(item, index) in orderItems"
            :key="index"
          >
            <view
              class="item-cont"
              :data-ordernum="item.primaryOrderNo"
              @tap="toOrderDetailPage"
            >
              <view class="prod-pic">
                <image :src="item.logo" />
              </view>
              <view class="prod-info">
                <view class="prodname">
                  {{ item.name }}
                </view>
                <view class="prod-info-cont">
                  {{ item.yColor }}，{{ item.ySize}}
                </view>
                <view class="price-nums">
                  <text class="prodprice">
                    <text class="symbol">
                      ￥
                    </text>
                    <text class="big-num">
                      {{ wxs.parsePrice(item.price)[0] }}
                    </text>
                    <text class="small-num">
                      .{{ wxs.parsePrice(item.price)[1] }}
                    </text>
                  </text>
                  <text class="prodcount">
                    x{{ item.num }}
                  </text>
                </view>
              </view>
            </view>
          </block>

          <view class="total-num">
            <text class="prodcount">
              共{{ totalCount }}件商品
            </text>
            <view class="prodprice">
              合计：
              <text class="symbol">
                ￥
              </text>
              <text class="big-num">
                {{ wxs.parsePrice(total)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(total)[1] }}
              </text>
            </view>
          </view>
        </view>
        <!-- 宝贝信息 -->
        <view class="boby-info" @tap="onAddInfo">
          <view>
            <text>宝贝信息</text>
          </view>
          <view class="item" v-if="babyInfo">
            <view>{{ babyInfo.name }} {{ babyInfo.phone }}</view>
            <view class="school">{{ babyInfo.schoolName }} {{ babyInfo.className }}</view>
          </view>
          <view class="tips" v-else>请录入宝贝信息</view>
          <view class="arrow" />
        </view>
        <!-- 订单详情 -->
        <view class="order-msg">
          <view class="msg-item">
            <view class="item">
              <text>买家留言</text>
              <input
                v-model="remarks"
                placeholder="给卖家留言"
              >
            </view>
          </view>
        </view>

        <view class="order-msg">
          <view class="msg-item">
            <view class="item">
              <view class="item-tit">
                订单总额
              </view>
              <view class="item-txt price">
                <text class="symbol">
                  ￥
                </text>
                <text class="big-num">
                  {{ wxs.parsePrice(total)[0] }}
                </text>
                <text class="small-num">
                  .{{ wxs.parsePrice(total)[1] }}
                </text>
              </view>
            </view>
            <view class="item">
              <view class="item-tit">
                运费
              </view>
              <view class="item-txt price">
                <text class="symbol">
                  ￥
                </text>
                <text class="big-num">
                  {{ wxs.parsePrice(transfee)[0] }}
                </text>
                <text class="small-num">
                  .{{ wxs.parsePrice(transfee)[1] }}
                </text>
              </view>
            </view>
            <view class="item payment">
              <view class="item-txt price">
                小计：
                <text class="symbol">
                  ￥
                </text>
                <text class="big-num">
                  {{ wxs.parsePrice(actualTotal)[0] }}
                </text>
                <text class="small-num">
                  .{{ wxs.parsePrice(actualTotal)[1] }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部栏 -->
      <view class="submit-order-footer">
        <view class="sub-order">
          <view class="item-txt">
            合计：
            <view class="price">
              <text class="symbol">
                ￥
              </text>
              <text class="big-num">
                {{ wxs.parsePrice(actualTotal)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(actualTotal)[1] }}
              </text>
            </view>
          </view>
        </view>
        <view
          class="footer-box"
          @tap="toPay"
        >
          提交订单
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
const wxs = number()
let orderEntry = '0' // 订单入口 0购物车 1立即购买
/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  orderEntry = options.orderEntry
})

const userAddr = ref(null)
const babyInfo = ref(null)
/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  const pages = getCurrentPages()
  const currPage = pages[pages.length - 1]
  if (currPage.selAddress === 'yes') {
    // 将携带的参数赋值
    userAddr.value = currPage.item
    babyInfo.value = currPage.infos
    console.log(userAddr.value, 222);
  }
  // 获取订单数据
  loadOrderData()
})

let couponIds = []
const coupons = ref({})
const total = ref(0)
const actualTotal = ref(0)
const orderItems = ref([])
const totalCount = ref(0)
const transfee = ref(0)
const remarks = ref('')
const infos = ref('')
const visible = ref(false)
const schoolInfo = ref({})
const ifBao = ref(null)
/**
 * 加载订单数据
 */
const addressId = ref('')
const openId = ref('')
const loadOrderData = () => {
  let addrId = 0
  if (userAddr.value != null) {
    addrId = userAddr.value.id
    addressId.value = addrId
  }
  openId.value = uni.getStorageSync('openId')
  orderItems.value = (JSON.parse(uni.getStorageSync('goodsList')))
  const { schoolId } = orderItems.value[0]
  ifBao.value = orderItems.value[0]?.ifBao
  if(ifBao.value == 1) {
    addressId.value = 0
  }
  if(schoolId || schoolId == 0){
    http.request({
      url: '/xcx/schoolList',
      method: 'POST',
      data: { schoolId }
    }).then(({ data }) => {
      data?.result?.map(m => {
        if(m.id == schoolId){
          schoolInfo.value = m
        }
      })
    })
  }
  if(orderEntry == 0) {
    const cartIds = orderItems.value?.map(m => { return m.id })
    const numList = orderItems.value?.map(m => { return m.num })
    totalCount.value = numList.reduce((accumulator, value) => {
        return accumulator + value;
    }, 0)
    uni.showLoading({
      mask: true
    })
    http.request({
      url: '/xcx/getPriceByCart',
      method: 'POST',
      data: {
        cartIds,
        openId: openId.value
      }
    }).then(({ data }) => {
      if(data?.key == 0) {
        uni.hideLoading()
        const { price, yPrice } = data?.result
        total.value = price
        transfee.value = yPrice
        actualTotal.value = price + yPrice
      }
    })
  } else {
    uni.showLoading({
      mask: true
    })
    const { prodId, num } = orderItems.value[0] ?? {}
    const goodsId = prodId
    totalCount.value = num
    http.request({
      url: '/xcx/getPriceByNow',
      method: 'POST',
      data: {
        goodsId,
        openId: openId.value,
        num
      }
    }).then(({ data }) => {
      if(data?.key == 0) {
        uni.hideLoading()
        const { price, yPrice } = data?.result
        total.value = price
        transfee.value = yPrice
        actualTotal.value = price + yPrice
      }
    })
  }
}
/**
 * 宝贝信息
 */
const onAddInfo = () => {
  uni.navigateTo({
    url: '/pages/infos/infos?babyInfo=' + JSON.stringify(babyInfo)
  })
}


/**
 * 提交订单
 */
const toPay = () => {
  if (ifBao.value == 0 && !userAddr.value) {
    uni.showToast({
      title: '请选择地址',
      icon: 'none'
    })
    return
  }
  if (!babyInfo.value) {
    uni.showToast({
      title: '请录入宝贝信息',
      icon: 'none'
    })
    return
  }
  submitOrder()
}

const submitOrder = () => {
  uni.showLoading({
    mask: true
  })
  let url = '', data = {
    openId: openId.value,
    addressId: ifBao.value == 1 ?  "0" : addressId.value ,
    remark: remarks.value,
    name: babyInfo.value.name,
    schoolId: babyInfo.value.schoolId,
    // cardNo: babyInfo.value.cardNo,
    classId: babyInfo.value.classId,
    phone: babyInfo.value.phone
  }
  if(orderEntry == 0) {
    // 购物车
    url = '/xcx/cartToOrder'
    data.cartIds = orderItems.value?.map(m => { return m.id })
  } else {
    // 直接购买
    url = '/xcx/buyNow'
    const { prodId, num, yColor, ySize } = orderItems.value[0] ?? {}
    totalCount.value = num
    data.num = num
    data.goodsId = prodId
    data.yColor = yColor
    data.ySize = ySize
  }
  uni.showLoading({
    mask: true
  })
  http.request({
    url,
    method: 'POST',
    data
  }).then(({ data }) => {
    if(data?.key == 0) {
      uni.hideLoading()
      normalPay(data?.result)
    }
  })
}
const showToast = (title) => {
  uni.showToast({
    title,
    icon: 'none',
    duration: 1500
  })
}
/**
 * 支付，直接提交成功
 * @param data
 */
const normalPay = (data) => {
  const orderInfo = {
      appId: data?.appid,
      nonceStr: data?.noncestr,
      package: data?.prepayid,
      paySign: data?.sign,
      signType: data?.signType,
      timeStamp: data?.timestamp?.toString()
    }
  console.log(orderInfo,111222);
  uni.showLoading({
    mask: true
  })
  uni.requestPayment({
    provider: 'wxpay',
    appId: data?.appid,
    nonceStr: data?.noncestr,
    package: data?.prepayid,
    paySign: data?.sign,
    signType: data?.signType,
    timeStamp: data?.timestamp?.toString(),
    success: function(res){
      uni.hideLoading()
      showToast('支付成功')
      setTimeout(() => {
        const orderNumbers = 1
        uni.navigateTo({
          url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers
        })
      }, 1200)
    },
    fail: function(res){
      showToast('支付失败，请重新支付')
    }
  })
}

const couponSts = ref(1)
const changeCouponSts = (e) => {
  couponSts.value = e.currentTarget.dataset.sts
}



/**
 * 去地址页面
 */
const toAddrListPage = () => {
  uni.navigateTo({
    url: '/pages/delivery-address/delivery-address?order=0'
  })
}

/**
 * 确定选择好的优惠券
 */
const choosedCoupon = () => {
  loadOrderData()
  popupShow.value = false
}

/**
 * 优惠券子组件发过来
 */
const checkCoupon = (e) => {
  const index = couponIds.indexOf(e.detail.couponId)
  if (index === -1) {
    couponIds.push(e.detail.couponId)
  } else {
    couponIds.splice(index, 1)
  }
}
</script>

<style scoped lang="scss">
@use './submit-order.scss';
</style>
